package com.vv.tools.modules.sys.controller;

import com.vv.tools.common.message.Result;
import com.vv.tools.common.message.ResultEnum;
import com.vv.tools.common.util.TokenUtil;
import com.vv.tools.modules.sys.entity.User;
import com.vv.tools.modules.sys.model.request.LoginRequest;
import com.vv.tools.modules.sys.service.CaptchaService;
import com.vv.tools.modules.sys.service.UserService;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "Login Controller")
@RestController
public class LoginController {

    @Resource
    private CaptchaService captchaService;

    @Resource
    private UserService userService;

    /**
     * 获取验证码
     */
    @Operation(summary = "获取验证码", description = "获取验证码")
    @GetMapping("/captcha.jpg")
    public void captcha(String uuid, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("/sys/login")
    public Result<String> login(@RequestBody LoginRequest request) {
        // 验证码
        boolean validate = captchaService.validate(request.getUuid(), request.getCaptcha());
        if (!validate) {
            return Result.fail(ResultEnum.AUTH_CAPTCHA_NOT_RIGHT);
        }

        //用户信息
        User user = userService.getByUsername(request.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.comparePassword(request.getPassword())) {
            return Result.fail(ResultEnum.AUTH_BAD_CREDENTIALS);
        }

        //生成token
        return Result.success(TokenUtil.genAccessToken(request.getUsername()));
    }

}
